import React, {useEffect, useState} from 'react'
import {connect} from 'umi'
import { Form, Button, Modal, Row, Col, Select, DatePicker, Input, message, Cascader } from 'antd'
import CreatePersonTable from './EditDegradeTable'
import SelectUserModal from "@/pages/components/SelectUserModal"
import { getProtocolPersonnel, getContractModelList } from '../../service'
import { PlusOutlined } from '@ant-design/icons'
import {getContractSubjectList} from "@/pages/Personnel/Entry/Contract/service";
import moment from 'moment'
import { trainingMethodTypes, trainingTypes } from '@/utils/constant'


const FormItem = Form.Item;
const {RangePicker} = DatePicker;
const {Option} = Select;

const formLayout = {
  labelCol: { span: 7 },
};
const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
}

const CreateForm = (props) => {
  const { onCancel, visible, current, onSubmit, isUpdate, global = {} } = props;
  const {options = {}} = global;
  const {nativePlace = []} = options;
  const [form] = Form.useForm();
  const [title, setTitle] = useState('');
  const [userModalVisible, setUserModalVisible] = useState(false);
  const [addUserList,setAddUserList] = useState([]);
  const [protocolUserItems,setProtocolUsers] = useState([]);
  const [contractData,setContractData] = useState([]);
  const [contractList,setContractList] = useState([]);


  useEffect(() => {
    if (visible){
      getContractModelList(1).then(res => {
        setContractList(res);
      });
      setTitle(isUpdate?'保存':'详情');
      //获取合同主体
      getContractSubjectList().then(res => {
        setContractData(res);
        if (current){
          current.trainingTime = [moment(current.trainingStartTime),moment(current.trainingEndTime)];
          current.signedTime = moment(current.signedTime);
          current.legalPerson = res.find(item => item.id === current.companyId)?.representative;
          if (typeof current.trainingLocation === 'string')
            current.trainingLocation = current.trainingLocation.split(',').map(item => parseInt(item));
          form.setFieldsValue(current);
          getProtocolPersonnel(current.id).then(res => {
            setProtocolUsers(res.map(item => ({
              ...item,
              key: item.oid,
              serviceTime: [moment(item.serviceStartTime), moment(item.serviceEndTime)]
            })))
          })
        }
      });
    }
  }, [visible]);

  const onFormCancel = () => {
    form.resetFields();
    setAddUserList([]);
    setProtocolUsers([]);
    onCancel()
  };

  const confirmSelectedUsers = (values) =>{
    setAddUserList(values);
    setUserModalVisible(false);
  };

  const getEnterpriseNatureInfo = (value,option) =>{
    form.setFieldsValue({enterpriseNature:option.lable.property,
      legalPerson:option.lable.representative,
      registeredAddress:option.lable.registeredAddress
    })
  };

  const saveProtocolUser = (values) => {
    let newProtocolUsers = [...values];
    setProtocolUsers(newProtocolUsers);
  };

  const handleSubmit = async () => {
    let id = current ? current.id : null;
    const filedValues = await form.validateFields();
    let trainingStartTime = filedValues.trainingTime[0];
    let trainingEndTime = filedValues.trainingTime[1];
    let trainingLocation = filedValues.trainingLocation.toString();
    let protocolPersonnelEntityArrayList = [];
    for( let item of protocolUserItems){
      if (!item.trainingFoodSpending || !item.trainingSpending
        || !item.trainingTotal || !item.serviceTime || item.serviceTime.length<2 ){
        message.error(`${item.name}存在未填项，请填写`);
        return;
      }
      item.serviceStartTime = item.serviceTime[0];
      item.serviceEndTime = item.serviceTime[1];
      protocolPersonnelEntityArrayList.push(item);
    }
    onSubmit({...filedValues, protocolPersonnelEntityArrayList, trainingStartTime, trainingEndTime, trainingLocation, id});
    form.resetFields();
    setAddUserList([]);
    setProtocolUsers([]);
  };

  const setNativePlaceLabel = (label) => {
    if (typeof label !== 'string') {
      return label.join('')
    } else {
      return [label].join('')
    }
  }

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="companyId" label="甲方主体"  rules={[{required: true, message: '甲方主体不能为空'}]}>
              <Select disabled={!isUpdate} placeholder="请选择甲方主体" onChange={getEnterpriseNatureInfo} showSearch filterOption={(input, option) =>
                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0} allowClear>
                { contractData.length>0 ? contractData.map((item, index) => {
                  return (
                    <Option value={item.id} key={index} lable={item}>
                      {item.name}
                    </Option>
                  )
                }) : ''}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="legalPerson" label="法人代表">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="projectName" label="项目名称" rules={[{required: true, message: '项目名称不能为空'}]}>
              <Input disabled={!isUpdate} />
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="trainingStructure" label="培训机构" rules={[{required: true, message: '培训机构不能为空'}]}>
              <Input disabled={!isUpdate} />
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="trainingTime" label="培训时间" rules={[{required: true, message: '培训时间不能为空'}]}>
              <RangePicker disabled={!isUpdate} className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="trainingType" label="培训类型" rules={[{required: true, message: '培训类型不能为空'}]}>
              <Select disabled={!isUpdate} placeholder="请选择培训类型" showSearch filterOption={(input, option) =>
                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0} allowClear>
                {
                  trainingTypes.map((item,index) => {
                    return <Option value={item.value} key={index}>{item.label}</Option>
                  })
                }
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="trainingMethod" label="培训方式" rules={[{required: true, message: '培训方式不能为空'}]}>
              <Select disabled={!isUpdate} placeholder="请选择培训方式" showSearch filterOption={(input, option) =>
                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0} allowClear>
                {
                  trainingMethodTypes.map((item,index) => {
                    return <Option value={item.value} key={index}>{item.label}</Option>
                  })
                }
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="trainingLocation" label="培训地点" rules={[{required: true, message: '培训地点不能为空'}]}>
              <Cascader disabled={!isUpdate} fieldNames={{ label: 'title', value: 'value', children: 'children' }}
                        displayRender={(label) => setNativePlaceLabel(label)} placeholder="请输入"
                        options={nativePlace}/>
              {/*<Input disabled={!isUpdate} />*/}
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="signedTime" label="签订合同日期" rules={[{required: true, message: '签订合同日期不能为空'}]}>
              <DatePicker disabled={!isUpdate} className='widthStyle' />
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="template" label="培训协议模板" rules={[{required: true, message: '培训协议模板不能为空'}]}>
              <Select disabled={!isUpdate} placeholder="请选择培训协议模板" showSearch filterOption={(input, option) =>
                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0} allowClear>
                {contractList.map((item, index) => {
                  return (
                    <Option value={item.id} key={index} lable={item}>
                      {item.name}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col span={24}>
            <FormItem name="protocolUsers">
              <CreatePersonTable hideOperate={!isUpdate} addUserList={addUserList} protocolUserItems={protocolUserItems} saveFunction={saveProtocolUser}/>
            </FormItem>
          </Col>
          {
            isUpdate && <Col span={24}>
              <Button style={{width: '100%', marginBottom: 8}} type="dashed" onClick={()=>setUserModalVisible(true)}>
                <PlusOutlined/>
                新增成员
              </Button>
            </Col>
          }
        </Row>
      </>
    )
  };

  const renderFooter = () => {
    return (
      <>
        <Button type="primary" onClick={() => onFormCancel()}>关闭</Button>
        {
          isUpdate && <Button type="primary" onClick={() => handleSubmit()}>确认</Button>
        }
      </>
    )
  };

  return (
    <Modal
      title={title}
      width={'90%'}
      visible={visible}
      footer={renderFooter()}
      onCancel={() => onFormCancel()}
    >
      <Form {...formLayout} form={form}>
        {renderContent()}
      </Form>

      <SelectUserModal
        selectType={1}
        visible={userModalVisible}
        handleOk={confirmSelectedUsers}
        handleCancel={()=>setUserModalVisible(false)}
      />
    </Modal>
  )
};


export default connect(({global}) => ({
  global
}))(CreateForm)
